package com.company;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @date : 2022/7/1 11:30
 * ArrayList线程不安全验证
 */

public class P020_ArrayListThreadUnsafe {

    public static void main(String[] args) {

        // 多线程会有空指针问题，会有下标越界异常
        List<Integer> list = new LinkedList<>();
        // 多线程会出现下标越界异常
//        List<Integer> list = new ArrayList<>();
        // 是个线程安全的类
//        List<Integer> list = new Vector<>();
        int count = 1000;
        CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            int a = i;
            new Thread(() -> {
                list.add(a);
                latch.countDown();
            }).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int num1 = 0;
        int num2 = 0;
        for (int i = 0; i < count; i++) {
            if (list.get(i) == null) {
//                System.out.println("i = " + i);
                num1++;
            } else {
                num2++;
            }
        }
        System.out.println(num1 + "+" + num2 + "=" + count);
        System.out.println(list.size());
    }
}
